package com.xueshishasha.oa.service.impl;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.xueshishasha.oa.common.utils.PageModel;
import com.xueshishasha.oa.service.DataService;


/**
 * @author xueshishasha
 *
 * @param <E>
 */
public class DataServiceImpl<E> extends HibernateDaoSupport implements DataService<E> {
	
	
	public Serializable save(E e){
		return getHibernateTemplate().save(e);
		
	}
	
	//getHibernateTemplate().findByCriteria(criteria)
	
	public void delete(E e){
		getHibernateTemplate().delete(e);
	}
	
	public void update(E e){
		getHibernateTemplate().update(e);
	}
	
	@SuppressWarnings("unchecked")
	public E getModelById(Class<E> clazz,Serializable id){
		return (E)getHibernateTemplate().get(clazz, id);
	}
	
	public void saveOrUpdate(E e){
		getHibernateTemplate().saveOrUpdate(e);
	}
	
	public void saveOrUpdateAll(Collection<E> ce){
		getHibernateTemplate().saveOrUpdateAll(ce);
	}

	@SuppressWarnings("unchecked")
    public List<E> getModels(String sql, Object[] parameters) {
        return this.getHibernateTemplate().find(sql, parameters);
    }

	@SuppressWarnings("unchecked")
	@Override
	public E getModel(String sql, Object[] parameters) {
		return (E)this.getHibernateTemplate().find(sql, parameters).get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<E> getByCriteria(DetachedCriteria dc) {
		return (List<E>)this.getHibernateTemplate().findByCriteria(dc);
	}

	@Override
	public Long getCount(Class<E> clazz) {
		String hql = "select count(*) from "+clazz.getSimpleName()+"  where name='乔学士'"; 
		  return  ((Long)getHibernateTemplate().iterate(hql).next()).longValue(); 
	}
	
    /**
     * @param detachedCriteria 条件
     * @return 满足条件的条数
     */
	public int getCountByCriteria(final DetachedCriteria detachedCriteria) {  
        Integer count = (Integer) getHibernateTemplate().executeWithNativeSession(new HibernateCallback(){
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				Criteria criteria = detachedCriteria.getExecutableCriteria(session);  
                return criteria.setProjection(Projections.rowCount()).uniqueResult();  
			}
        });
        return count.intValue(); 
    }
	
	/**
	 * @param detachedCriteria 条件
	 */
	@SuppressWarnings({"unchecked" })
	public List findAllByCriteria(final DetachedCriteria detachedCriteria) {  
		
		return (List) getHibernateTemplate().executeWithNativeSession(new HibernateCallback() {  
			public Object doInHibernate(Session session) throws HibernateException {  
				Criteria criteria = detachedCriteria.getExecutableCriteria(session);  
				return criteria.list();  
			}  
		});  
	}  
	
	//==============================分页查询===================================

    
    
    @SuppressWarnings("unchecked")
	public PageModel list(final String hql, final Object[] paras,
			final int offset, final int count) {
    	
    	String wherehql = "select count(*) "+hql;
		Integer totalCount = ((Number) getHibernateTemplate().iterate(wherehql,
				paras).next()).intValue();
		
		List list = getHibernateTemplate().executeFind(
				new HibernateCallback() {
					@Override
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
						Query query = (Query) session.createQuery(hql);
						if (paras != null) {
							for (int i = 0; i < paras.length; i++) {
								query.setParameter(i, paras[i]);
							}
						}
						query.setFirstResult(offset);
						query.setMaxResults(count);
						return query.list();
					}
				});
		PageModel pageModel = new PageModel(list, totalCount, count, offset/10+1);

		System.out.println("=============================================");
		System.out.println(pageModel.getList().size());
		System.out.println("=============================================");
		return pageModel;
	}
  

    
}
